<template>
  <div class="addGoods">
    <base-template :breadList="['商品管理', '添加商品']">
      <el-alert title="添加商品信息" center :closable="false"></el-alert>

      <!-- 步骤条 -->
      <el-steps :active="active - 0" finish-status="success" :align-center="true">
        <el-step title="基本信息" icon="el-icon-loading"> </el-step>

        <el-step title="商品参数" icon="el-icon-loading"></el-step>
        <el-step title="商品属性" icon="el-icon-loading"></el-step>
        <el-step title="商品图片" icon="el-icon-loading"></el-step>
        <el-step title="商品内容" icon="el-icon-loading"></el-step>
      </el-steps>

      <el-form :model="addForm" status-icon :rules="rules" ref="ruleForm" label-width="80px" label-position="top" label-suffix=" :">
        <el-tabs tab-position="left" v-model="active" @tab-click="changeTab" :before-leave="beforeLeave">
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="goods_price">
              <el-input type='number' v-model="addForm.goods_price"></el-input>
            </el-form-item>

            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type='number' v-model="addForm.goods_weight"></el-input>
            </el-form-item>

            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addForm.goods_number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类" >
              <el-cascader v-model="selectValue" :options="cascaderData" :props="props" @change="handleChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 动态属性 -->
          <el-tab-pane label="商品参数">
            <div v-for="(item, index) in checkList" :key="item.attr_id" class="checkbox_group">
              <h3>{{ item.attr_name }}</h3>
              <el-checkbox-group v-model="checkList[index].attr_vals" @change="checkboxChange">
                <el-checkbox :label="i" v-for="(i, index) in item.attr_vals" :key="index"></el-checkbox>
              </el-checkbox-group>
            </div>
          </el-tab-pane>

          <!-- 静态属性 -->
          <el-tab-pane label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in staticData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 上传图片 -->
          <el-tab-pane label="商品图片">
            <el-upload :action="action" :on-preview="handlePreview" :on-remove="handleRemove" 
			:headers="headers"
			:on-success='onSuccess'
			list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>


          <!-- 编辑内容 -->
          <el-tab-pane label="商品内容">
			  <h3>添加商品描述：</h3>
			  <quill-editor v-model='addForm.goods_introduce'></quill-editor>
		  <button @click='submitAddGoods'>添加商品</button>

		  </el-tab-pane>
        </el-tabs>
      </el-form>
    </base-template>
	<el-dialog :visible.sync="dialogVisible">
  <img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
  </div>
</template>

<script>
//局部引入富文本编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
 
import BaseTemplate from '../../component/base-template.vue'
export default {
  components: {
    BaseTemplate,
    quillEditor,

  },
  data() {
    return {
      active: '0', //活跃
      addForm: {
        //绑定上传所需对象
        goods_name: '',
        goods_cat: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: '',
        attrs: '',
      },
      rules: {
        goods_name: [{ required: true, message: '请填写商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请填写商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请填写商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请填写商品重量', trigger: 'blur' }],
      },
      selectValue: [], //级联绑定
      cascaderData: [], //级联遍历数据
      props: {
        expandTrigger: 'hover',
        label: 'cat_name',
        children: 'children',
        value: 'cat_id',
      },
      checkList: [], //checkBox 多选
      staticData: [],//静态
	  action:'http://127.0.0.1:8888/api/private/v1/upload',
	  fileList:[],
	  headers:{
		 Authorization:sessionStorage.getItem('token')
	  },

		//预览图片
	  dialogVisible:false,
	  dialogImageUrl:'',
    }
  },
  computed: {
    tempId() {
      //得到级联id
      if (this.selectValue.length > 2) {
        return this.selectValue[2]
      } else {
        return 0
      }
    },
  },
  created() {
    this.getCascaderData()
  },
  methods: {
    handleChange(val) {
      if (val.length < 3) {
        this.$message.error('只允许选择三级标题')
        this.selectValue = []
      }
    },
    async getCascaderData() {
      this.cascaderData = await this.$store.dispatch('getRequest', { path: '/categories' })
    },
    beforeLeave(active, old) {
    //   if (old == 0) {
    //     if (this.selectValue.length != 3) {
    //       this.$message.error('请选择商品分类')
    //       return false
    //     }
    //   }
      console.log(active, old)
    },
    async changeTab(active, event) {
      if (active.index == 1) {
        const res = await this.$store.dispatch('getRequest', { path: `/categories/${this.tempId}/attributes`, params: { sel: 'many' } })

        for (let prop in res) {
          res[prop].attr_vals = res[prop].attr_vals.split(' ')
        }
        this.checkList = res

        console.log(res)
      } else if (active.index == 2) {
        this.staticData = await this.$store.dispatch('getRequest', { path: `/categories/${this.tempId}/attributes`, params: { sel: 'only' } })
      }
    },
    checkboxChange(val) {
      console.log(val)
    },
	handlePreview(file){  //上传
		 this.dialogImageUrl = file.url;
        this.dialogVisible = true;
	},
	handleRemove(file){
		console.log(file);
	},
	onSuccess(res,file){
		console.log(res);
		
	},
	submitAddGoods(){
		// 合并attrs参数
		let temp1=JSON.parse(JSON.stringify(this.checkList))
		temp1.forEach((item)=>{
			item.attr_vals=item.attr_vals.join(' ')
		})
		let temp=[...temp1,...this.staticData] 
	// 合并goods_cat
		let tempGoods_cat=this.selectValue.join(',')

		const obj=Object.assign({},this.addForm,{goods_cat:tempGoods_cat,attrs:temp})
		this.$refs.ruleForm.validate(async valid=>{
			if(valid){
				const {meta,data}=	await this.$store.dispatch('postRequest',{path:'/goods',params:obj})
				if(meta.status==201){
					this.$message.success('添加商品成功')
					this.$refs.ruleForm.resetFields()
					this.$router.replace('/home/goods')
				}else{
					this.$message.error('添加商品失败，请检查')
				}
			}else{
				this.$message.error('请填写完整')
			}
		})
	

	}
  },
}
</script>

<style lang="less" scoped>
.el-input {
  width: 300px;
}
div.checkbox_group {
  margin-top: 10px;
}

</style>
